Skip to content

ScrollAreaTocWidget

Base classes

Name Children Inherits
TreeView
prettyqt.widgets.treeview
Default model/view implementation of a tree view.

â‹” Inheritance diagram

graph TD
  1656082603["custom_widgets.ScrollAreaTocWidget"]
  1283923056["widgets.TreeView"]
  1058239441["widgets.TreeViewMixin"]
  3836649406["widgets.AbstractItemViewMixin"]
  1259044718["widgets.AbstractScrollAreaMixin"]
  1689631995["widgets.FrameMixin"]
  829357528["widgets.WidgetMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  625385617["gui.PaintDeviceMixin"]
  2426194723["QtWidgets.QTreeView"]
  3038536384["QtWidgets.QAbstractItemView"]
  1459025998["QtWidgets.QAbstractScrollArea"]
  3822057598["QtWidgets.QFrame"]
  3620195106["QtWidgets.QWidget"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  673956333["QtGui.QPaintDevice"]
  1283923056 --> 1656082603
  1058239441 --> 1283923056
  3836649406 --> 1058239441
  1259044718 --> 3836649406
  1689631995 --> 1259044718
  829357528 --> 1689631995
  3227531497 --> 829357528
  2751680898 --> 3227531497
  625385617 --> 829357528
  2751680898 --> 625385617
  2751680898 --> 829357528
  2751680898 --> 1689631995
  2751680898 --> 1259044718
  2751680898 --> 3836649406
  2751680898 --> 1058239441
  2426194723 --> 1283923056
  3038536384 --> 2426194723
  1459025998 --> 3038536384
  3822057598 --> 1459025998
  3620195106 --> 3822057598
  3984060476 --> 3620195106
  37984305 --> 3984060476
  2751680898 --> 37984305
  673956333 --> 3620195106
  37984305 --> 673956333

🛈 DocStrings

Bases: TreeView

Source code in prettyqt/custom_widgets/scrollareatocwidget.py
class ScrollAreaTocWidget(widgets.TreeView):
    section_changed = core.Signal()

    ScrollMode = ScrollMode
    core.Enum(ScrollMode)

    def __init__(
        self,
        scrollarea: widgets.ScrollArea,
        orientation: (
            constants.Orientation | constants.OrientationStr
        ) = constants.VERTICAL,
        widget_class: type[widgets.QWidget] = widgets.QWidget,
        **kwargs,
    ) -> None:
        """A TreeView which can show a Table-of-contents list based on a given ScrollArea.

        With default settings, it will scan the widgets contained in the scrollArea for
         a windowTitle.
        These widgets will be shown in the TreeView, and the TreeView selection will be
        synced to what is currently visible in the ScrollArea.
        This basically emulates the behaviour of many websites
        (like the [Qt Website][https://doc.qt.io/qt-6/supported-platforms.html])
        or from VS code settings.

        You can set up the Toc Tree by passing a ScrollArea instance:

        ```py
        widget = widgets.Widget()
        layout = widget.set_layout("horizontal")
        scrollarea = widgets.ScrollArea()
        # add some widgets to the ScrollArea here
        # ...
        toc = ScrollAreaTocWidget(scrollarea)
        layout.add(toc)
        layout.add(scrollarea)
        ```

        The Toc tree can be configured to use other properties for populating
        than windowTitle.
        You can also set a widget class filter if you only want a specific widget
        class to be shown.

        The widget supports 3 different scroll modes:

        1) Single: Only one row in the Tree will be highlighted. (the one which equals
        the topmost one from the scrollArea)
        2) Multi: All rows which equal to visible widgets in the ScrollArea will be shown.
        3) HeadersOnly: like Single, but only highlights top-level widgets from the
                        ScrollArea.

        There are also two different expand modes to choose from:

        1) ExpandAll: All subsections are always expanded.
        2) on_focus: Only the section containing the focused item is expanded.

        This widget is used by [ConfigWidget](ConfigWidget.md).
        """
        # TODO: not sure if parent should always equal scrollarea..."""
        self._WidgetClass = widget_class
        self._scroll_mode = ScrollMode.Single
        self._always_expanded = False
        self._last_visible = None
        self.scrollarea = scrollarea
        super().__init__(scrollarea, **kwargs)
        self._orientation = constants.ORIENTATION.get_enum_value(orientation)
        self.setFixedWidth(200)
        self.h_header.hide()
        self.h_header.setStretchLastSection(True)
        self.setAlternatingRowColors(False)
        self.setRootIsDecorated(False)
        # self.setStyleSheet(
        #     """::item:hover {background: transparent; border-color:transparent}
        #     ::item:selected { border-color:transparent;
        #     border-style:outset; border-width:2px; color:black; }"""
        # )
        if self._orientation == constants.VERTICAL:
            scrollarea.v_scrollbar.valueChanged.connect(self._on_scroll)
        else:
            scrollarea.h_scrollbar.valueChanged.connect(self._on_scroll)
        self.set_widget(scrollarea)

    def _get_map(self):
        maps = super()._get_map()
        maps |= {"scrollMode": SCROLL_MODE}
        return maps

    def showEvent(self, event):
        super().showEvent(event)
        self._on_scroll()

    # @classmethod
    # def setup_example(cls):
    #     scrollarea = widgets.ScrollArea()
    #     w = widgets.Widget()
    #     scrollarea.set_widget(w)
    #     return cls(scrollarea)

    def set_widget(self, widget: widgets.ScrollArea):
        """Set the ScrollArea widget to follow."""
        if (inner := widget.widget()) is None:
            msg = "No widget set on ScrollArea."
            raise RuntimeError(msg)
        self.scrollarea = widget
        model = ScrollAreaTocModel(
            inner,
            show_root=True,
            parent=self.scrollarea,
            widget_class=self._WidgetClass,
        )
        self.set_model(model)
        self.proxy = self.proxifier.set_sort_filter_proxy(
            recursive_filtering_enabled=True
        )
        self.proxy.set_filter_case_sensitive(False)
        self.show_root(False)
        inner.installEventFilter(self)
        self.selectionModel().currentRowChanged.connect(self._on_current_change)
        self.selectionModel().selectionChanged.connect(self._on_selection_change)
        # if self._always_expanded:
        self.expandAll()

    def _on_current_change(self, new, old):
        if self.model() is None:
            return
        is_vertical = self._orientation == constants.VERTICAL
        area = self.scrollarea
        scrollbar = area.v_scrollbar if is_vertical else area.h_scrollbar
        with self.signal_blocked(scrollbar.valueChanged, self._on_scroll):
            widget = self.model().data(new, role=constants.USER_ROLE)
            area.scroll_to_bottom()
            area.ensureWidgetVisible(widget, 10, 10)

    def _on_selection_change(self, new, old):
        if self.model() is None:
            return
        selected_widgets = [i.data(constants.USER_ROLE) for i in self.selected_indexes()]
        source_model = self.get_model(skip_proxies=True)
        if isinstance(source_model, ScrollAreaTocModel):
            source_model.set_highlighted_widgets(selected_widgets)

    def _on_scroll(self):
        model = cast("core.AbstractItemModel | None", self.model())
        if model is None:
            return
        visible_widgets = self.scrollarea.get_visible_widgets(typ=self._WidgetClass)
        if not visible_widgets or visible_widgets == self._last_visible:
            return
        self._last_visible = visible_widgets
        sig = self.selectionModel().currentRowChanged
        with self.signal_blocked(sig, self._on_current_change):
            self.select_index(None)
            if not self._always_expanded:
                self.collapseAll()
            match self.get_scroll_mode():
                case "multi":
                    indexes = model.search_tree(visible_widgets, role=constants.USER_ROLE)
                    for index in indexes:
                        children = model.get_child_indexes(index)
                        # only select if all children selected.
                        # if all(c in indexes for c in children):

                        # highlight when no children or when first child is visible.
                        if not children or children[0] in indexes:
                            self.select_index(index, clear=False)
                        self.set_expanded(indexes)
                        self.scroll_to(indexes[0])
                        self.scroll_to(indexes[-1])
                case "headers_only":
                    if indexes := model.search_tree(
                        visible_widgets,
                        role=constants.USER_ROLE,
                        max_results=1,
                    ):
                        self.set_current_index(indexes[0])
                        self.scroll_to(indexes[0])
                case "single":
                    if indexes := model.search_tree(
                        visible_widgets, role=constants.USER_ROLE
                    ):
                        viewport = self.scrollarea.viewport()
                        # sort indexes by closest distance to top
                        indexes.sort(
                            key=lambda x: abs(
                                x
                                .data(constants.USER_ROLE)
                                .map_to(viewport, x.data(constants.USER_ROLE).rect())
                                .top()
                            ),
                        )
                        self.collapseAll()
                        self.model().fetchMore(indexes[0])
                        self.set_current_index(indexes[0])
                        self.scroll_to(indexes[0])
                case _:
                    raise ValueError(self._scroll_mode)
        # model.set_highlighted_indexes(indexes)

    def wheelEvent(self, e):
        self.scrollarea.wheelEvent(e)

    def eventFilter(self, source: core.QObject, event: core.QEvent) -> bool:
        match event.type():
            case core.Event.Type.ChildAdded:
                self._on_scroll()
        return False

    def _scrollMode(self) -> ScrollMode:
        return self._scroll_mode

    def get_scroll_mode(self) -> ScrollModeStr:
        return SCROLL_MODE.inverse[self._scrollMode()]

    def set_scroll_mode(self, mode: ScrollMode | ScrollModeStr):
        self._scroll_mode = SCROLL_MODE.get_enum_value(mode)

    def is_always_expanded(self) -> bool:
        return self._always_expanded

    def set_always_expanded(self, always_expanded: bool):
        self._always_expanded = always_expanded

    scrollMode = core.Property(  # noqa: N815
        enum.Enum,
        _scrollMode,
        set_scroll_mode,
        doc="Scrolling mode",
    )
    always_expanded = core.Property(
        bool,
        is_always_expanded,
        set_always_expanded,
        doc="Whether the tree is always expanded.",
    )

__init__(scrollarea: widgets.ScrollArea, orientation: constants.Orientation | constants.OrientationStr = constants.VERTICAL, widget_class: type[widgets.QWidget] = widgets.QWidget, **kwargs) -> None

A TreeView which can show a Table-of-contents list based on a given ScrollArea.

With default settings, it will scan the widgets contained in the scrollArea for a windowTitle. These widgets will be shown in the TreeView, and the TreeView selection will be synced to what is currently visible in the ScrollArea. This basically emulates the behaviour of many websites (like the [Qt Website][https://doc.qt.io/qt-6/supported-platforms.html]) or from VS code settings.

You can set up the Toc Tree by passing a ScrollArea instance:

widget = widgets.Widget()
layout = widget.set_layout("horizontal")
scrollarea = widgets.ScrollArea()
# add some widgets to the ScrollArea here
# ...
toc = ScrollAreaTocWidget(scrollarea)
layout.add(toc)
layout.add(scrollarea)

The Toc tree can be configured to use other properties for populating than windowTitle. You can also set a widget class filter if you only want a specific widget class to be shown.

The widget supports 3 different scroll modes:

1) Single: Only one row in the Tree will be highlighted. (the one which equals the topmost one from the scrollArea) 2) Multi: All rows which equal to visible widgets in the ScrollArea will be shown. 3) HeadersOnly: like Single, but only highlights top-level widgets from the ScrollArea.

There are also two different expand modes to choose from:

1) ExpandAll: All subsections are always expanded. 2) on_focus: Only the section containing the focused item is expanded.

This widget is used by ConfigWidget.

Source code in prettyqt/custom_widgets/scrollareatocwidget.py
def __init__(
    self,
    scrollarea: widgets.ScrollArea,
    orientation: (
        constants.Orientation | constants.OrientationStr
    ) = constants.VERTICAL,
    widget_class: type[widgets.QWidget] = widgets.QWidget,
    **kwargs,
) -> None:
    """A TreeView which can show a Table-of-contents list based on a given ScrollArea.

    With default settings, it will scan the widgets contained in the scrollArea for
     a windowTitle.
    These widgets will be shown in the TreeView, and the TreeView selection will be
    synced to what is currently visible in the ScrollArea.
    This basically emulates the behaviour of many websites
    (like the [Qt Website][https://doc.qt.io/qt-6/supported-platforms.html])
    or from VS code settings.

    You can set up the Toc Tree by passing a ScrollArea instance:

    ```py
    widget = widgets.Widget()
    layout = widget.set_layout("horizontal")
    scrollarea = widgets.ScrollArea()
    # add some widgets to the ScrollArea here
    # ...
    toc = ScrollAreaTocWidget(scrollarea)
    layout.add(toc)
    layout.add(scrollarea)
    ```

    The Toc tree can be configured to use other properties for populating
    than windowTitle.
    You can also set a widget class filter if you only want a specific widget
    class to be shown.

    The widget supports 3 different scroll modes:

    1) Single: Only one row in the Tree will be highlighted. (the one which equals
    the topmost one from the scrollArea)
    2) Multi: All rows which equal to visible widgets in the ScrollArea will be shown.
    3) HeadersOnly: like Single, but only highlights top-level widgets from the
                    ScrollArea.

    There are also two different expand modes to choose from:

    1) ExpandAll: All subsections are always expanded.
    2) on_focus: Only the section containing the focused item is expanded.

    This widget is used by [ConfigWidget](ConfigWidget.md).
    """
    # TODO: not sure if parent should always equal scrollarea..."""
    self._WidgetClass = widget_class
    self._scroll_mode = ScrollMode.Single
    self._always_expanded = False
    self._last_visible = None
    self.scrollarea = scrollarea
    super().__init__(scrollarea, **kwargs)
    self._orientation = constants.ORIENTATION.get_enum_value(orientation)
    self.setFixedWidth(200)
    self.h_header.hide()
    self.h_header.setStretchLastSection(True)
    self.setAlternatingRowColors(False)
    self.setRootIsDecorated(False)
    # self.setStyleSheet(
    #     """::item:hover {background: transparent; border-color:transparent}
    #     ::item:selected { border-color:transparent;
    #     border-style:outset; border-width:2px; color:black; }"""
    # )
    if self._orientation == constants.VERTICAL:
        scrollarea.v_scrollbar.valueChanged.connect(self._on_scroll)
    else:
        scrollarea.h_scrollbar.valueChanged.connect(self._on_scroll)
    self.set_widget(scrollarea)

set_widget(widget: widgets.ScrollArea)

Set the ScrollArea widget to follow.

Source code in prettyqt/custom_widgets/scrollareatocwidget.py
def set_widget(self, widget: widgets.ScrollArea):
    """Set the ScrollArea widget to follow."""
    if (inner := widget.widget()) is None:
        msg = "No widget set on ScrollArea."
        raise RuntimeError(msg)
    self.scrollarea = widget
    model = ScrollAreaTocModel(
        inner,
        show_root=True,
        parent=self.scrollarea,
        widget_class=self._WidgetClass,
    )
    self.set_model(model)
    self.proxy = self.proxifier.set_sort_filter_proxy(
        recursive_filtering_enabled=True
    )
    self.proxy.set_filter_case_sensitive(False)
    self.show_root(False)
    inner.installEventFilter(self)
    self.selectionModel().currentRowChanged.connect(self._on_current_change)
    self.selectionModel().selectionChanged.connect(self._on_selection_change)
    # if self._always_expanded:
    self.expandAll()

:fa-brands-github: Show source on GitHub